import webapp2
import cgi
import os
import json
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import images
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app


class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')
class DisplayAllImage (webapp2.RequestHandler):
    def get(self):
        self.response.write("<html><body>")
        images = ImageData.all()
        self.response.write("""<table>
                <thead>
                    <td>Author</td>
                    <td>Title</td>
                    <td>Image</td>
                    <td>Date</td>
                </thead>
                <tbody>""")
        for image in images:
            author = image.author and image.author.nickname() or "Anonymous"
            self.response.write("<tr>")
            self.response.write("<td>%s</td>" %author)
            self.response.write("<td>%s</td>" %cgi.escape(image.title))
            self.response.write("<td><img src='img?img_id=%s' /> </td>" %image.key())
            self.response.write("<td>%s</td>" %image.date)
            self.response.write("</tr>")
        self.response.write("</tbody></table>")
        self.response.write("</body></html>")
        
class UploadImage2(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('<html><h5>This page is for upload image</h5>')
        self.response.out.write("""
          <form action="/handler" enctype="multipart/form-data" method="post">
            <div><label>Message:</label></div>
            <div><label>Avatar:</label></div>
            <div><input type="file" name="img"/></div>
            <div><input type="submit" value="Sign Guestbook" /></div>
          </form>
        </body>
      </html>""")
class UploadImage(webapp2.RequestHandler):
    def get(self):
        if (users.get_current_user()):
            url_auth = users.create_login_url(self.request.uri)
            url_linktext = "Log in"
        else:
            url_auth = users.create_logout_url(self.request.uri)
            url_linktext = "Log out"
        template_params = {
            'url_auth': url_auth,
            'url_display': '/display',
            'url_handler': '/handler',
            'url_linktext': url_linktext,
        }
        path = os.path.join(os.path.dirname(__file__),"index.html")
        self.response.out.write(template.render(path,template_params))
            
                
class UploadImageHandler(webapp2.RequestHandler):
    def post(self):
        image = ImageData()
        if (users.get_current_user()):
            image.author = users.get_current_user()
        photo = self.request.get("pic")
        image.photo = db.Blob(photo)
        
        #Get file name
        """form = cgi.FieldStorage()
        img = form['img']"""
        values = self.request.POST.itervalues()
        for value in values:
            if isinstance(value, cgi.FieldStorage):
                filename = value.filename
        if (filename):
            image.title = filename
        image.put()
        obj = json.dumps('{"status" : "Upload successfully }')
        self.response.write(obj)
        #self.redirect('/display')
        
        
class ImageData(db.Model):
    author = db.UserProperty()
    title = db.StringProperty()
    photo = db.BlobProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    
class Image(webapp2.RequestHandler):
    def get(self):
        image = db.get(self.request.get("img_id"))
        if image.photo:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(images.resize(image.photo,50,50))
        else:
            self.response.out.write("No image")
route = [
         ('/', MainPage),
         ('/upload', UploadImage),
         ('/upload2', UploadImage2),
         ('/handler', UploadImageHandler),
         ('/display',DisplayAllImage),
         ('/img',Image)
         ]
application = webapp2.WSGIApplication(route, debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
